package browser;

/* 
 * Author: rendy.jr
 * Date: Jun 10, 2011
 * 6.005 Elements of Software Construction
 * Rendy Bambang Junior
 * rendy.jr@gmail.com
 * 
 * Page class represent a webpage. It contains URL and content.
 * Responsible for :
 * - manage browser cache
 * 
 */

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

public class Page {
	// page attribute
	protected URL url;
	protected String content;
	
	//constructor based on url in string form
	public Page(String urlString) throws MalformedURLException, IOException{
		this.url = new URL(urlString);
		download();
	}
	
	//get URL from this page
	public URL getURL(){
		return this.url;
	}
	
	//get content from this page
	public String getContent(){
		return this.content;
	}
	
	/* try to get page from cache if exist */
	public static Page getPageFromCache(String urlString) throws MalformedURLException, IOException{
		return Browser.cache.get(urlString);
	}
	
	/* put page in cache */
	public static void putPageInCache(Page p){
		Browser.cache.put(p);
	}
	
	// fetch page from cache if exist, from server if doesn't
	protected void download() throws MalformedURLException, IOException{
		Page p = getPageFromCache(url.toString()); 
		if (p != null){ 
			this.content = p.content; 
		} else { 
			this.content = Browser.fetch(url.toString()); 
			putPageInCache(this); 
		}
	}
}
